package com.inwavetech.os.util.field.dynamicfields;

import com.inwavetech.os.util.field.Field;
import com.inwavetech.os.util.field.FieldsCollection;

/**
 * Created by jgskin on 2/17/14.
 */
public class EntityUpdatableFields {

    protected final FieldsCollection fields;
    private final Object entity;
    private final Class clazz;

    public EntityUpdatableFields(Object entity, FieldsCollection fields) {
        this.entity = entity;
        this.fields = fields;
        clazz = entity.getClass();
    }

    public void updateEntityValues() throws NoSuchFieldException, IllegalAccessException {
        for (String fieldKey: fields.keySet()) {
            java.lang.reflect.Field entityField = null;
            entityField = clazz.getDeclaredField(fieldKey);
            entityField.setAccessible(true);

            Field field = fields.get(fieldKey);

            entityField.set(entity, field.getValue());
        }
    }

    public void updateFields() throws NoSuchFieldException, IllegalAccessException {
        for (String fieldKey: fields.keySet()) {
            Field field = fields.get(fieldKey);
            field.setValue(clazz.getDeclaredField(fieldKey).get(entity));
        }
    }
}
